package co.laomag.coffee.service.admins.impl;

import cn.hutool.crypto.digest.DigestUtil;
import co.laomag.coffee.dao.admins.*;
import co.laomag.coffee.model.entity.AdAdminRole;
import co.laomag.coffee.model.entity.AdRole;
import co.laomag.coffee.model.entity.AdRoleMenu;
import co.laomag.coffee.model.entity.Admin;
import co.laomag.coffee.model.vo.AdMenuVo;
import co.laomag.coffee.model.vo.AdminVo;
import co.laomag.coffee.model.vo.Message;
import co.laomag.coffee.service.admins.AdminService;
import co.laomag.coffee.utils.CreatTree;
import co.laomag.coffee.utils.RedisUtils;
import co.laomag.coffee.utils.ResultUtils;
import co.laomag.coffee.utils.TokenUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 马泽朋
 * @version 1.0
 * @date 2020/4/18 下午 3:09
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class AdminServiceImpl implements AdminService {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private AdminDao adminDao;
    @Resource
    private AdAdminRoleDao adAdminRoleDao;
    @Resource
    private AdRoleDao adRoleDao;
    @Resource
    private AdRoleMenuDao adRoleMenuDao;
    @Resource
    private AdMenuDao adMenuDao;

    /**
     * 查询管理员
     *
     * @param phone    手机号,账号
     * @param password 密码
     * @return Message
     */
    @Override
    public Message administratorLogin(String phone, String password) {
         int code = 424;
         String info = "账号或者密码错误";
         Object data = null;
        AdminVo adminVo = adminDao.selectByPhone(phone);
        if (adminVo != null){
            boolean equals = adminVo.getPassword().equals(DigestUtil.md5Hex(password));
            if (equals){
                Boolean aBoolean = redisUtils.verificationToken("admin-"+ adminVo.getPhone());
                if (aBoolean){
                    String value = redisUtils.getValue("admin-"+adminVo.getPhone());
                    redisUtils.deleteToken(value);
                    redisUtils.deleteToken(adminVo.getPhone());
                }
                code = 201;
                info = "登录成功";
                String token = TokenUtils.createToken(adminVo);

                adminVo.setToken(token);
                data = adminVo;
                redisUtils.saveToken(adminVo);
            }else {
                code = 424;
                info = "账号或者密码错误";
            }
        }else {
            code = 424;
            info = "账号或者密码错误";
        }
        return ResultUtils.message(code, info,data);
    }

    /**
     * 新增管理员
     *
     * @param admin 管理员对象
     * @return 成功大于0, 失败小于0
     */
    @Override
    public Message addAdministrator(Admin admin) throws Exception {
        Message message = null;
        //对密码进行MD5加密
        admin.setPassword(DigestUtil.md5Hex(admin.getPassword()));
        int insert = adminDao.insertSelective(admin);
        System.out.println(admin);
        AdAdminRole adAdminRole = new AdAdminRole();
        adAdminRole.setRoleId(admin.getRoleID());
        adAdminRole.setAdminId(admin.getAid());
        int i = adAdminRoleDao.insertSelective(adAdminRole);
        if (insert>0){
            message = ResultUtils.message(200, "添加成功");
        }else {
            message = ResultUtils.message(425, "添加失败");
        }
        return message;
    }

    /**
     * 更新用户信息
     *
     * @param admin
     * @return
     */
    @Override
    public Message update(Admin admin) throws Exception {
        try {
            int i = adminDao.updateByPrimaryKey(admin);
            AdAdminRole adAdminRole = new AdAdminRole();
            adAdminRole.setAdminId(admin.getAid());
            adAdminRole.setRoleId(admin.getRoleID());
            int i1 = adAdminRoleDao.updateByPrimaryKey(adAdminRole);
        }catch (Exception e){
            throw new Exception();
        }
        return ResultUtils.message(200, "修改成功");
    }

    /**
     * 根据前端传来的Token查询用户权限
     *
     * @param token
     * @return
     */
    @Override
    public Message getRouters(String token) {
        Message message = null;
        Map<String,Object> map = new HashMap<>();
        AdminVo admin = redisUtils.getAdmin(token);
        if (admin != null){
            List<AdMenuVo> adMenuVoList = new ArrayList<>();
            // 我是管理员的ID
            Integer aid = admin.getAid();
            // 通过管理员id拿到管理员用户中间表
            AdAdminRole adAdminRole = adAdminRoleDao.selectByPrimaryKey(aid);
            // 通过管理员中间表拿到角色表
            AdRole adRole = adRoleDao.selectByPrimaryKey(adAdminRole.getRoleId());
            List<AdRoleMenu> adRoleMenus = adRoleMenuDao.selectByRoleId(adRole.getRid());
            for (AdRoleMenu adRoleMenu : adRoleMenus) {
                AdMenuVo adMenuVo = adMenuDao.selectByMenuId(adRoleMenu.getMenuId());
                if (adMenuVo != null){
                    adMenuVoList.add(adMenuVo);
                }
            }
            List<AdMenuVo> adMenuVoList1 = CreatTree.listToTree(adMenuVoList);
            map.put("adMenuVoList",adMenuVoList1);
            System.out.println(JSON.toJSONString(adMenuVoList1));
            map.put("admin",admin);
            message = ResultUtils.message(200, "",map);

        }else {
            message = ResultUtils.message(50008, "非法的Token");
        }
        return message;
    }

    @Override
    public AdRole getRoles(int aid) {
        try {
            AdAdminRole adAdminRole = adAdminRoleDao.selectByPrimaryKey(aid);
            AdRole adRole = adRoleDao.selectByPrimaryKey(adAdminRole.getRoleId());
            if (adRole != null){
                return  adRole;
            }
        }catch (Exception e){

        }
        return null;
    }

    @Override
    public Message getRoles() {
        List<AdRole> roles = adRoleDao.getRoles();
        return ResultUtils.message(200, "查询成功",roles);
    }

    /**
     * 查询所有的管理员带分页
     *
     * @param title 查询参数
     * @param page  第几页
     * @param limit 每页记录数
     * @param token
     * @return 结果
     */
    @Override
    public Message getAdminList(String title, int page, int limit,String token) {
        // 判断是否右查询条件
        if (title != null){
           title = "%" + title + "%";
        }
        AdminVo currentUser = redisUtils.getAdmin(token);
        // 查询总记录数
        int total = adminDao.getTotal(title,currentUser.getAid());
        List<Admin> admins = adminDao.selectAdmin(title, (page-1)*limit, limit,currentUser.getAid());
        for (Admin admin : admins) {
            AdRole roles = getRoles(admin.getAid());
            admin.setRole(roles.getRoles());
            admin.setRoleID(roles.getRid());
        }
        Map<String, Object> map= new HashMap<>(2);
        map.put("total", total);
        map.put("items", admins);
        return  ResultUtils.message(200, "查询成功", map);
    }

    /**
     * 删除管理员
     *
     * @param admin
     * @return
     */
    @Override
    public Message deleteAdmin(Admin admin) throws Exception {
        int i = adminDao.deleteByPrimaryKey(admin.getAid());
        return ResultUtils.message(200, "删除成功");
    }
}
